package de.ifi.lmu.snitzelhunt.view;

import java.io.File;
import java.util.ArrayList;

import de.ifi.lmu.snitzelhunt.R;
import de.ifi.lmu.snitzelhunt.basics.ImageTask;
import de.ifi.lmu.snitzelhunt.basics.Task;
import de.ifi.lmu.snitzelhunt.util.GSonUtility;
import de.ifi.lmu.snitzelhunt.util.ImageServerUtility;
import de.ifi.lmu.snitzelhunt.util.responses.AsyncServer_Image_UploadResponse;
import de.ifi.lmu.snitzelhunt.util.responses.Server_Image_UploadResponse;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Class handles the usage of images. 
 * A person an upload a picture either taken by himself or chosen from gallery.
 * 
 * @author Sarah
 * 
 */
public class Activity_ImageTask extends ActionBarActivity implements
		AsyncServer_Image_UploadResponse {

	ImageView view;
	Bitmap bmp;
	String filepath = null;
	static final int REQUEST_IMAGE_CAPTURE = 1;
	static final int REQUEST_PICK_IMAGE = 2;
	private ImageTask tempTask;
	private String imageTask;
	private ArrayList<Task> tampList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_activity__image_task);

		view = (ImageView) findViewById(R.id.imageViewImageTask);
		bmp = null;
		tempTask = new ImageTask(0, 0, "", 0);
		tampList = new ArrayList<Task>();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity__image_task, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}


/**
 * Method uploads an image to server
 *  
 * @param v
 */
	public void uploadandGPS(View v) {

		final ImageButton weiter = (ImageButton) findViewById(R.id.Button_ImageSpeichern);
		weiter.setBackgroundResource(R.drawable.weiter_dark);

		final EditText imagetext = (EditText) findViewById(R.id.TextViewAufgabeImage);

		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			public void run() {
				weiter.setBackgroundResource(R.drawable.weiter);

				if (imagetext.getText().equals("")) {
					
					Toast toast = Toast.makeText(getApplicationContext(),
							"Du hast noch keinen Text erstellt",
							Toast.LENGTH_SHORT);
					toast.show();
				}

				else {
					if (filepath != null) {
						
						System.out.println("With text");
						
						new ImageServerUtility().uploadImage(filepath,
								Activity_ImageTask.this);
					} else {
						Toast toast = Toast.makeText(getApplicationContext(),
								"Du hast noch kein Bild ausgew�hlt!", Toast.LENGTH_SHORT);
						toast.show();
					}

				}
			}
		}, 200);

	}

	/**
	 * method opens the camera and a picture can be taken. The picture is saved to phones gallery and sets the image
	 * to the view
	 * @param v
	 */
	public void takePicture(View v) {

		final ImageButton kamera = (ImageButton) findViewById(R.id.Button_ImageCamera);
		kamera.setBackgroundResource(R.drawable.kamera_dark);
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			public void run() {

				kamera.setBackgroundResource(R.drawable.kamera);

				if (getPackageManager().hasSystemFeature(
						PackageManager.FEATURE_CAMERA)) {
					Log.i("snitzel util", "kamera vorhanden");
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					File f = new File(android.os.Environment
							.getExternalStorageDirectory(), "temp.jpg");
					intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
					startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
				}

				else {
					Toast toast = Toast.makeText(getApplicationContext(),
							"keine Kamera vorhanden", Toast.LENGTH_SHORT);
					toast.show();
				}

			}
		}, 200);

	}

	/**
	 * Method opens the phones gallery, so the user can choose a picture which is displayed in the view
	 * @param v
	 */
	public void goToGallery(View v) {

		final ImageButton gallery = (ImageButton) findViewById(R.id.Button_ImageGallery);
		gallery.setBackgroundResource(R.drawable.image_gallery_dark);
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			public void run() {

				gallery.setBackgroundResource(R.drawable.image_gallery);

				Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
				photoPickerIntent.setType("image/*");
				startActivityForResult(photoPickerIntent, REQUEST_PICK_IMAGE);
			}
		}, 200);

	}

	/* (non-Javadoc)
	 * @see android.support.v4.app.FragmentActivity#onActivityResult(int, int, android.content.Intent)
	 */
	/* (non-Javadoc)
	 * @see android.support.v4.app.FragmentActivity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_PICK_IMAGE)
			if (resultCode == RESULT_OK) {
				Uri selectedImage = data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };
				Cursor csr = getContentResolver().query(selectedImage,
						filePathColumn, null, null, null);
				csr.moveToFirst();
				filepath = csr.getString(csr.getColumnIndex(filePathColumn[0]));
				csr.close();
				bmp = ImageServerUtility.decodeSampledBitmapfromFile(filepath, 200, 200);
				view.setBackgroundResource(R.drawable.imagefield_empty);
				view.setImageBitmap(bmp);
			}
		if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
			
			File f = new File(Environment.getExternalStorageDirectory()
					.toString());
			for (File temp : f.listFiles()) {
				if (temp.getName().equals("temp.jpg")) {
					f = temp;
					break;
				}
			}
			filepath = f.getAbsolutePath();
			bmp = BitmapFactory.decodeFile(filepath);
			view.setBackgroundResource(R.drawable.imagefield_empty);
			view.setImageBitmap(bmp);
		}
	}
	
	public void fieldNotFilled() {
		Toast toast = Toast
				.makeText(getApplicationContext(),
						"Du hast noch keinen Image-Task erstellt!",
						Toast.LENGTH_SHORT);

		LinearLayout toastLayout = (LinearLayout) toast.getView();
		TextView toastTV = (TextView) toastLayout.getChildAt(0);
		toastTV.setTextSize(20);

		toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL,
				0, 0);

		toast.show();
	}

	/**
	 * Upload an image to the server. If successful, add Imagetask to tasklist of the route
	 */
	@Override
	public void processServer_Image_UploadResponse(
			Server_Image_UploadResponse response) {
		if (response.getHttpStatus() == 200) {
			Log.i("snitzel", "saved to " + response.getImageID());

			
			imageTask = ((EditText) findViewById(R.id.TextViewAufgabeImage))
					.getText().toString();

			Log.i("Image-Task: ", imageTask);
			// �berpr�fe auf leere Felder
			if (imageTask.equals("")) {
				fieldNotFilled();
			} else {
				// set Action
				tempTask.setAction(imageTask);
				tempTask.setGlobalImgID(response.getImageID());
				// put in tampTask
				tampList.add(tempTask);

				final ImageButton weiter = (ImageButton) findViewById(R.id.Button_ImageSpeichern);
				weiter.setBackgroundResource(R.drawable.weiter_dark);
				Handler handler = new Handler();
				handler.postDelayed(new Runnable() {
					public void run() {

						Intent intent = new Intent(Activity_ImageTask.this,
								Activity_GPS.class);
						intent.putExtra("TaskInfo",
								GSonUtility.serializeTaskList(tampList));
						startActivity(intent);
						weiter.setBackgroundResource(R.drawable.weiter);
					}
				}, 100);
			}
		}
			
		 else {
			Toast.makeText(
					getApplicationContext(),
					"Der Upload ist fehlgeschlagen, probier es sp�ter noch einmal",
					Toast.LENGTH_SHORT).show();
		}

	}
}
